package com.ilop.sthome.mvp.present.scene;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.example.common.base.OnCallBackToRefresh;
import com.example.common.mvp.BasePresenterImpl;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.data.enums.SmartDevice;
import com.ilop.sthome.data.greenDao.AutomationBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.data.greenDao.SceneBean;
import com.ilop.sthome.mvp.contract.scene.AutomationContract;
import com.ilop.sthome.common.command.SendAutoCommand;
import com.ilop.sthome.ui.activity.scene.ChooseActionActivity;
import com.ilop.sthome.ui.activity.scene.InputDetailActivity;
import com.ilop.sthome.ui.activity.scene.SettingActionActivity;
import com.ilop.sthome.ui.activity.scene.SettingHumitureActivity;
import com.ilop.sthome.ui.activity.scene.SettingTempControlActivity;
import com.ilop.sthome.ui.activity.scene.SettingTimingActivity;
import com.ilop.sthome.ui.dialog.BaseDialog;
import com.ilop.sthome.utils.CoderUtils;
import com.ilop.sthome.utils.greenDao.utils.AutomationDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.SceneDaoUtil;
import com.ilop.sthome.utils.tools.ByteUtil;
import com.siterwell.familywellplus.R;


import java.util.ArrayList;
import java.util.List;

/**
 * @Author skygge.
 * @Date on 2020-01-25.
 * @Dec:
 */
public class AutomationPresenter extends BasePresenterImpl<AutomationContract.IView> implements AutomationContract.IPresent {

    private Context mContext;
    private String mDeviceName;
    private int mDeleteSceneId;
    private int mPosition;
    private String mAutoCode;
    private boolean mIsNewAdd = false;
    private boolean mModify = false;

    private SceneBean mScene;
    private AutomationBean mAutomation;
    private SendAutoCommand mSendSceneData;

    private List<DeviceInfoBean> inputShow;
    private List<DeviceInfoBean> outputShow;

    public AutomationPresenter(Context mContext, String deviceName) {
        this.mContext = mContext;
        this.mDeviceName = deviceName;
        mScene = SceneDaoUtil.getInstance().findSceneByChoice(mDeviceName);
        DeviceInfoBean mDeviceInfoBean = DeviceDaoUtil.getInstance().findGatewayByDeviceName(mDeviceName);
        mSendSceneData = new SendAutoCommand(mContext, mDeviceInfoBean);
    }

    @Override
    public void isDefault(AutomationBean auto) {
        if (auto!=null) {
            mView.showIsDefault("00".equals(auto.getReserve()));
        }else {
            mView.showIsDefault(true);
        }
    }

    @Override
    public void isNewForShow(AutomationBean mAuto) {
        this.mAutomation = mAuto;
        mIsNewAdd = true;
        setInputList(mAutomation.getInputList());
        setOutputList(mAutomation.getOutputList());
    }

    @Override
    public void isModifyForShow(boolean modify, AutomationBean mAutomation) {
        mModify = modify;
        if (!modify){
            this.mAutomation = new AutomationBean();
            mIsNewAdd = true;
            inputShow = new ArrayList<>();
            outputShow = new ArrayList<>();
        }else {
            this.mAutomation = mAutomation;
            setInputList(mAutomation.getInputList());
            setOutputList(mAutomation.getOutputList());
        }
    }

    @Override
    public void setInputList(List<DeviceInfoBean> deviceList) {
        inputShow = deviceList;
        mView.showInputList(deviceList);
    }

    @Override
    public void setOutputList(List<DeviceInfoBean> deviceList) {
        outputShow = deviceList;
        mView.showOutputList(deviceList);
    }

    @Override
    public boolean isTimerOrClick() {
        for (DeviceInfoBean mDevice: inputShow) {
            if ("TIMER".equals(mDevice.getDevice_type()) || "CLICK".equals(mDevice.getDevice_type())){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean isTimer() {
        for (DeviceInfoBean mDevice: inputShow) {
            if ("TIMER".equals(mDevice.getDevice_type())){
                return true;
            }
        }
        return false;
    }

    @Override
    public void addNewInput() {
        Intent addItem = new Intent(mContext, ChooseActionActivity.class);
        addItem.putExtra(CommonId.KEY_INPUT, true);
        addItem.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
        mView.startActivityByIntent(addItem);
    }

    @Override
    public void addNewOutput() {
        Intent addItem = new Intent(mContext, ChooseActionActivity.class);
        addItem.putExtra(CommonId.KEY_INPUT, false);
        addItem.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
        mView.startActivityByIntent(addItem);
    }

    @Override
    public void updateAction(boolean isInput, int position) {
        this.mPosition = position;
        DeviceInfoBean device;
        if (isInput){
            device = inputShow.get(position);
        }else {
            device = outputShow.get(position);
        }
        if ("CLICK".equals(device.getDevice_type())){
            Intent intent = new Intent(mContext, InputDetailActivity.class);
            intent.putExtra(CommonId.KEY_DEVICE_TYPE, "CLICK");
            mView.startActivityByIntent(intent);
        }else if ("TIMER".equals(device.getDevice_type())){
            Intent intent = new Intent(mContext, SettingTimingActivity.class);
            intent.putExtra(CommonId.KEY_UPDATE, true);
            intent.putExtra(CommonId.KEY_DEVICE, device);
            mView.startActivityByIntent(intent);
        }else if ("PHONE".equals(device.getDevice_type())){
            Intent intent = new Intent(mContext, InputDetailActivity.class);
            intent.putExtra(CommonId.KEY_DEVICE_TYPE, "PHONE");
            mView.startActivityByIntent(intent);
        }else {
            Intent intent = new Intent();
            intent.putExtra(CommonId.KEY_INPUT, isInput);
            intent.putExtra(CommonId.KEY_UPDATE, true);
            intent.putExtra(CommonId.KEY_DEVICE, device);

            if(!TextUtils.isEmpty(device.getProductKey()) || "GATEWAY".equals(device.getDevice_type())){
                intent.setClass(mContext, SettingActionActivity.class);
                mView.startActivityByIntent(intent);
            }else if(SmartDevice.EE_DEV_TH_CHECK == SmartDevice.getType(device.getDevice_type())){
                intent.setClass(mContext, SettingHumitureActivity.class);
                mView.startActivityByIntent(intent);
            }else if(SmartDevice.EE_TEMP_CONTROL == SmartDevice.getType(device.getDevice_type())){
                intent.setClass(mContext, SettingTempControlActivity.class);
                mView.startActivityByIntent(intent);
            }else {
                intent.setClass(mContext, SettingActionActivity.class);
                mView.startActivityByIntent(intent);
            }
        }
    }

    @Override
    public void deleteCondition(boolean isInput) {
        if (isInput){
            inputShow.remove(mPosition);
            setInputList(inputShow);
        }else {
            outputShow.remove(mPosition);
            setOutputList(outputShow);
        }
    }

    @Override
    public void onSaveAutomation() {
        if (checkContent()){
            if(!mModify){
                boolean isTimer = isTimer();
                String mSceneCode = CoderUtils.setSceneCode(mScene.getSid());
                String sceneHex = isTimer ? "7FFF" : Integer.toHexString(Integer.parseInt(mSceneCode, 2));
                mAutomation.setDeviceName(mDeviceName);
                mAutomation.setSceneId(sceneHex);
                String finalCode = CoderUtils.getNewCode(sceneHex ,inputShow, outputShow);
                String finalCRC = ByteUtil.stringToCRC(finalCode);
                mAutoCode = "FFFF" + finalCode + finalCRC;
                mSendSceneData.increaseAutomation(mAutoCode.toUpperCase());
                mAutomation.setCrcCord(finalCRC);
            }else {
                boolean isTimer = isTimer();
                String sceneHex = isTimer ? "7FFF" : mAutomation.getSceneId();
                String autoId = CoderUtils.setCodeSupplement2Byte(Integer.toHexString(mAutomation.getMid()));
                String finalCode = CoderUtils.getNewCode(sceneHex ,inputShow, outputShow);
                String finalCRC = ByteUtil.stringToCRC(finalCode);
                mAutoCode = autoId + finalCode + finalCRC;
                mSendSceneData.updateAutomation(mAutoCode.toUpperCase());
                mAutomation.setCrcCord(finalCRC);
                mAutomation.setSceneId(sceneHex);
            }
            mView.showSaveUnableToClick();
        }
    }

    @Override
    public void onDeleteAutomation(int sceneId) {
        mDeleteSceneId = sceneId;
        mSendSceneData.deleteAutomation(sceneId);
    }

    @Override
    public void sendSuccess(String autoId) {
        try{
            mAutomation.setCode(mAutoCode);
            mAutomation.setReserve("00");
            mAutomation.setInputList(inputShow);
            mAutomation.setOutputList(outputShow);

            if(!mModify){
                int mAutoId = Integer.parseInt(autoId, 16);
                mAutomation.setMid(mAutoId);
                mAutomation.setAutomationOnly(mDeviceName + "-" + mAutoId);
                AutomationDaoUtil.getInstance().getAutomationDao().insert(mAutomation);
            }else{
                AutomationDaoUtil.getInstance().getAutomationDao().update(mAutomation);
            }
            mView.finishActivity();
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }

    @Override
    public void deleteSuccess() {
        if(mDeleteSceneId>-1){
            AutomationDaoUtil.getInstance().deleteByMid(mDeleteSceneId, mDeviceName);
            mDeleteSceneId = -1;
            mView.finishActivity();
        }
    }

    @Override
    public boolean checkContent() {
        if (inputShow.size() == 0){
            mView.showToastMsg(mContext.getString(R.string.intput_must_has_eq));
            return false;
        }else if (outputShow.size() == 0){
            mView.showToastMsg(mContext.getString(R.string.output_must_has_eq));
            return false;
        }else {
            return true;
        }
    }

    @Override
    public boolean checkInput(DeviceInfoBean device) {
        if (inputShow.size()>0) {
            if ("CLICK".equals(device.getDevice_type()) || "TIMER".equals(device.getDevice_type())){
                mView.showToastMsg(mContext.getString(R.string.condition_cant_selected));
                return false;
            }
            for (DeviceInfoBean input : inputShow) {
                if (input.getDevice_type().equals(device.getDevice_type()) &&
                        input.getDevice_status().equals(device.getDevice_status())) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public boolean checkOutput(DeviceInfoBean device) {
        for (int i = 0; i < outputShow.size(); i++) {
            if ("PHONE".equals(device.getDevice_type())){
                if ("PHONE".equals(outputShow.get(i).getDevice_type())){
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void checkUpdateInput(DeviceInfoBean device) {
        inputShow.set(mPosition, device);
        setInputList(inputShow);
    }

    @Override
    public void checkUpdateOutput(DeviceInfoBean device) {
        outputShow.set(mPosition, device);
        setOutputList(outputShow);
    }

    @Override
    public void whetherToSave(boolean hasModify) {
        if (mIsNewAdd || hasModify){
            BaseDialog mDialog = new BaseDialog(mContext, new OnCallBackToRefresh() {
                @Override
                public void onConfirm() {
                    onSaveAutomation();
                }

                @Override
                public void onCancel() {
                    mView.finishActivity();
                }
            });
            mDialog.setMsg(mContext.getString(R.string.scene_has_modify));
            mDialog.show();
        }else {
            mView.finishActivity();
        }
    }
}
